package stardust.product.platform.persistence;


import javax.sql.DataSource;

import stardust.product.platform.persistence.sql.SQLFactory;
import stardust.product.platform.persistence.transaction.TransactionManager;


public class DataAccessFactory
{
	
	private static DataAccessFactory dataAccessFactory;
	
	private ThreadLocal<TransactionManager> localTransactionManager = new ThreadLocal<TransactionManager>();
	
	private DataSource dataSource;
	
	private SQLFactory sqlFactory;
	
	private DataAccessFactory() throws PersistenceException
	{
		if (DataAccessFactory.dataAccessFactory == null)
		{
			DataAccessFactory.dataAccessFactory = this;
		}
		else
		{
			throw new PersistenceException("数据访问上下文已经存在。");
		}
	}
	
	public DataAccessFactory(DataSource dataSource, SQLFactory sqlFactory) throws PersistenceException
	{
		this();
		this.dataSource = dataSource;
		this.sqlFactory = sqlFactory;
	}
	
	public static DataAccessFactory getDataAccessFactory()
	{
		return DataAccessFactory.dataAccessFactory;
	}
	
	public TransactionManager getTransactionManager()
	{
		if (this.localTransactionManager.get() == null)
		{
			this.localTransactionManager.set(new TransactionManager(this));
		}
		
		return this.localTransactionManager.get();
	}
	
	public DataAccess createDataAccess()
	{
		return new DataAccess(this);
	}
	
	public DataSource getDataSource()
	{
		return this.dataSource;
	}

	public void setDataSource(DataSource dataSource)
	{
		this.dataSource = dataSource;
	}

	public SQLFactory getSqlFactory()
	{
		return this.sqlFactory;
	}

	public void setSqlFactory(SQLFactory sqlFactory)
	{
		this.sqlFactory = sqlFactory;
	}
	
}
